package top.aoyudi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.tools.javac.Main;
import top.aoyudi.entity.User;
import top.aoyudi.service.IUserService;
import top.aoyudi.utils.YamlUtils;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;


public class UserServiceImpl implements IUserService {
    public Boolean getUser(User loginUser) throws URISyntaxException, IOException {
        // 获取yml配置文件
        File yml = new File(Objects.requireNonNull(Main.class.getClassLoader().getResource("config.yml")).toURI());
        YamlUtils.setYmlFile(yml);
        List<User> userList = switch (loginUser.getUserRole()) {
            case "20231111" -> (List<User>) YamlUtils.getByKey("user.administrator");
            case "20232222" -> (List<User>) YamlUtils.getByKey("user.admin");
            case "20233333" -> (List<User>) YamlUtils.getByKey("user.user");
            default -> null;
        };
        if (userList == null) {
            return false;
        }
        // 遍历list
        for (Object object : userList) {
            // 将list中的数据转成json字符串
            String jsonObject = JSON.toJSONString(object);
            // 将json转成需要的对象
            User user = JSONObject.parseObject(jsonObject, User.class);
            // 判断配置文件中是否有该用户。
            if (user.getAccount().equals(loginUser.getAccount()) && user.getPassword().equals(loginUser.getPassword())) {
                User.activeUser = user;
                return true;
            }
        }
        return false;
    }

    /**
     * 登录
     *
     * @throws URISyntaxException
     * @throws IOException
     */
    public static void login() throws URISyntaxException, IOException {
        // 使用Scanner(System.in)来接收用户输入的行数据
        Scanner scanner = new Scanner(System.in);
        User user = new User();
        boolean loginFlag = false;
        while (!loginFlag) {
            System.out.print("****输入账号：");
            user.setAccount(scanner.nextLine());
            System.out.print("****输入密码：");
            user.setPassword(scanner.nextLine());
            System.out.print("****输入角色编号：");
            user.setUserRole(scanner.nextLine());
            IUserService userService = new UserServiceImpl();
            if (userService.getUser(user)) {
                System.out.println("登陆成功正在进入文件系统");
                loginFlag = true;
            } else {
                System.out.println("\n\n****未找到用户信息，请重新登录****\n\n");
            }
        }
    }
}
